package star.cloud.asme.base.security.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Service;
import star.cloud.asme.system.user.User;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import static io.jsonwebtoken.Jwts.*;

@Service
public class JWTService {
    private static final String SECRET_KEY = "5368566D597133743677397A244326452948404D635166546A576E5A72347537";

    public String generateToken(Map<String, Object> extraClaims, User user) {
        return builder()//
                .claims(extraClaims)//
                .subject(user.getUsername())//
                .issuedAt(new Date(System.currentTimeMillis()))//
                .expiration(new Date(System.currentTimeMillis() + 14 * 24 * 60 * 60 * 1000))//
                .signWith(getSigningKey()).compact();
    }

    @SuppressWarnings("ALL")
    public String generateToken(User user) {
        return generateToken(new HashMap<>(), user);
    }

    public boolean isTokenValid(String token, User user) {
        final String username = extractUsername(token);
        return (username.equals(user.getUsername())) && !isTokenExpired(token);
    }

    public boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser().verifyWith(getSigningKey()).build()//
                .parseSignedClaims(token).getPayload();
    }

    private SecretKey getSigningKey() {
        byte[] keyBytes = Decoders.BASE64.decode(SECRET_KEY);
        return Keys.hmacShaKeyFor(keyBytes);
    }


    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    @SuppressWarnings("ALL")
    public Long extractUserId(String token) {
        String userIdStr = extractClaim(token, Claims::getId);
        return Long.parseLong(userIdStr);
    }

}